//
//  ThemeHelper.swift
//  aishop
//
//  Created by tuguowei on 2025/10/15.
//

import Foundation
import SwiftUI

class ThemeHelper {
    static let shared = ThemeHelper()
    
    private let cacheKey = "theme_config_value"
    private init() {}
    
    // 获取主题配置并保存
    func loadThemeConfig() async {
        do {
            let response = try await APIService.shared.fetchThemeConfig()
            if response.isSuccess, let config = response.data {
                // 保存到本地
                UserDefaults.standard.set(config.value, forKey: cacheKey)
                print("✅ 主题配置已保存: \(config.value)")
            }
        } catch {
            print("❌ 获取主题配置失败: \(error)")
        }
    }
    
    // 获取主题颜色
    func getThemeColor() -> String {
        let value = UserDefaults.standard.string(forKey: cacheKey) ?? "1"
        
        let colors = [
            "1": "#e93323",  // theme1
            "2": "#fe5c2d",  // theme2
            "3": "#42ca4d",  // theme3
            "4": "#1ca5e9",  // theme4
            "5": "#ff448f"   // theme5
        ]
        
        return colors[value] ?? colors["1"]!
    }
    
    // 获取SwiftUI Color
    func getColor() -> Color {
        return Color(hex: getThemeColor())
    }
    
    // 获取主题背景图片URL
    func getRightBgImageURL() -> String {
        let value = UserDefaults.standard.string(forKey: cacheKey) ?? "1"
        
        let imageNames = [
            "1": "right_red.png",
            "2": "right_orange.png",
            "3": "right_green.png",
            "4": "right_blue.png",
            "5": "right_pink.png"
        ]
        
        let imageName = imageNames[value] ?? "right_red.png"
        return "https://shopgo.ttxcx.net/crmebimage/presets/\(imageName)"
    }
}

// Color扩展
extension Color {
    init(hex: String) {
        let hex = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
        var int: UInt64 = 0
        Scanner(string: hex).scanHexInt64(&int)
        let a, r, g, b: UInt64
        switch hex.count {
        case 3: // RGB (12-bit)
            (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
        case 6: // RGB (24-bit)
            (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
        default:
            (a, r, g, b) = (1, 1, 1, 0)
        }

        self.init(
            .sRGB,
            red: Double(r) / 255,
            green: Double(g) / 255,
            blue:  Double(b) / 255,
            opacity: Double(a) / 255
        )
    }
}